package com.eshopkeeper.service.sys;

import com.baomidou.mybatisplus.plugins.Page;
import com.eshopkeeper.core.base.BaseService;
import com.eshopkeeper.core.support.Assert;
import com.eshopkeeper.core.support.email.Email;
import com.eshopkeeper.core.support.ldap.SystemSetting;
import com.eshopkeeper.core.support.login.LoginHelper;
import com.eshopkeeper.core.support.login.ThirdPartyUser;
import com.eshopkeeper.core.util.EmailUtil;
import com.eshopkeeper.core.util.WebUtil;
import com.eshopkeeper.core.util.yunzhi.StringUtil;
import com.eshopkeeper.model.sys.SysUser;
import com.eshopkeeper.model.sys.ext.SysUserBean;
import com.eshopkeeper.provider.sys.ISysUserProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author chenshufeng
 * @Description: 用户
 * @date 2017年3月7日
 */
@Service
public class SysUserService extends BaseService<ISysUserProvider, SysUser> {

    @Autowired
    public void setProvider(ISysUserProvider provider) {
        this.provider = provider;
    }
    
    public int addSysUser(SysUser sysUser) {
    	if (StringUtils.isNotBlank(sysUser.getPassword())) {
    		sysUser.setPassword(encryptPassword(sysUser.getPassword()));
    	} else {
    		sysUser.setPassword(encryptPassword("111111"));
    	}
    	return provider.insertSysUser(sysUser);
    }

    /**
     * 修改用户信息
     */
    @Transactional
    public void updateUserInfo(SysUser sysUser) {
        Assert.notNull(sysUser.getId(), "USER_ID");
        Assert.isNotBlank(sysUser.getAccount(), "ACCOUNT");
//        Assert.length(sysUser.getAccount(), 3, 15, "ACCOUNT");
        if (StringUtils.isNotBlank(sysUser.getPassword())) {
        	sysUser.setPassword(encryptPassword(sysUser.getPassword()));
        } else {
//        	sysUser.setPassword(encryptPassword("111111"));
        }
        
        SysUser user = this.queryById(sysUser.getId());
        Assert.notNull(user, "USER", sysUser.getId());
        if (StringUtils.isBlank(sysUser.getPassword())) {
            sysUser.setPassword(user.getPassword());
        }
        if (StringUtils.isEmpty(sysUser.getAvatar())) {
            sysUser.setAvatar(user.getAvatar());
        }
        sysUser.setUpdateBy(WebUtil.getCurrentUser());
        provider.update(sysUser);
        int roleCount = provider.updateUserRole(sysUser);
        if (roleCount<1) {
            throw new IllegalArgumentException("更新角色权限有误");
        }
    }

    public Page<SysUserBean> queryBeans(Map<String, Object> params) {
        return provider.queryBeans(params);
    }

    /**
     * 修改密码
     */
    public void updatePassword(Long id, String password) {
//        Assert.notNull(id, "USER_ID");
        Assert.isNotBlank(password, "PASSWORD");
        Long userId = WebUtil.getCurrentUser();

        SysUser sysUser = provider.queryById(userId);
        Assert.notNull(sysUser, "USER", userId);
//        Long userId = WebUtil.getCurrentUser();
//        if (!id.equals(userId)) {
//            SysUser user = provider.queryById(userId);
//            if (user.getUserType() == 1) {
//                throw new UnauthorizedException();
//            }
//        }
        sysUser.setPassword(encryptPassword(password));
        sysUser.setUpdateBy(WebUtil.getCurrentUser());
        provider.update(sysUser);
    }

    public String encryptPassword(String password) {
        return provider.encryptPassword(password);
    }

    public void thirdPartyLogin(ThirdPartyUser thirdUser) {
        SysUser sysUser = null;
        // 查询是否已经绑定过
        Long userId = provider.queryUserIdByThirdParty(thirdUser.getOpenid(), thirdUser.getProvider());
        if (userId == null) {
            sysUser = insertThirdPartyUser(thirdUser);
        } else {
            sysUser = queryById(userId);
        }
        LoginHelper.login(sysUser.getAccount(), sysUser.getPassword());
    }

    public SysUser insertThirdPartyUser(ThirdPartyUser thirdUser) {
        return provider.insertThirdPartyUser(thirdUser);
    }




	public void updateEnable(Map<String, Object> paramMap) {
		//Assert.notNull(id, "USER_ID");
        //Assert.notNull(enable, "ENABLE");
        //SysUser sysUser = provider.queryById(id);
        //Assert.notNull(sysUser, "USER", id);
        //sysUser.setEnable(enable);
        provider.updateSysUser(paramMap);
	}

    /**
     * 更改用户头像
     */
    public void updateFace(Map<String, Object> paramMap) {

        provider.updateFace(paramMap);
    }

    /**
     * Reset password string.
     * 重置密码
     * @param id the id
     * @param emailName
     *@param emailPassword @return the string
     */
    public String resetPassword(Long id, SystemSetting emailName, SystemSetting emailPassword) {

        //生成6位随机密码
        String password = makePassword();

        //根据id查询用户信息
        SysUser sysUser = provider.queryUserById(id);

        //如果为空返回1.表示没用查询到用户
        if (StringUtil.isEmpty(sysUser.getAccount())) {
            return "1";
        }

        sysUser.setId(id);
        sysUser.setPassword(encryptPassword(password));
        sysUser.setUpdateBy(WebUtil.getCurrentUser());

        //判断email是否为空.如果为空返回错误信息
        if (StringUtil.isEmpty(sysUser.getEmail())) {
            return "3";
        }
        //执行重置密码.
        int count = provider.resetPassword(sysUser);

        //成功则返回0并执行发送邮件步骤 失败返回2
        if (count > 0 ) {
            String body = "您的密码已经重置成功,账号:"+sysUser.getAccount()+",密码:"+password;
            Email email = new Email(emailName.getSystemSettingValue(), sysUser.getEmail(), null, "蜂巢后台密码重置", body, null);
            email.setHost("smtp.exmail.qq.com");
            email.setName(emailName.getSystemSettingValue());
            email.setPassword(emailPassword.getSystemSettingValue());
            email.setKey("resetPassword");
            Boolean aa = EmailUtil.sendEmail(email);
            return "0";
        } else {
            return "2";
        }
    }

    /*
    * 随机密码生成器
    * */
    public static String makePassword () {
        char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', 'A','B','C','D','E','F','G','H','I','J','K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y' ,'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        while (stringBuffer.length() < 6) {
            int i = random.nextInt(str.length);
            stringBuffer.append(str[i]);
        }
        return stringBuffer.toString();
    }

	public List<Map<String, Object>> getUserList() throws Exception {
		return provider.getUserList();
	}
	
}
